<template>
    <div class="card">
        <!-- <el-descriptions title="total" :column="5" border>
            <el-descriptions-item label="单项选择题" label-align="center" align="center">20</el-descriptions-item>
            <el-descriptions-item label="多项选择题" label-align="center" align="center">00</el-descriptions-item>
            <el-descriptions-item label="填空题" label-align="center" align="center">00</el-descriptions-item>
            <el-descriptions-item label="判断题" label-align="center" align="center">100</el-descriptions-item>
            <el-descriptions-item label="大题" label-align="center" align="center">00</el-descriptions-item>
        </el-descriptions> -->
        <selectFromBank :resetBtn="true" :addBtn="true" :loadBtn="true" :dataArr="dataArr" @Refresh="Refresh">
            <template #editBtn="{ row }">
                <el-button type="primary" plain size="mini" @click="addOrEditItem(row)">编辑</el-button>
            </template>
            <template #deleteBtn="{ row }">
                <el-button type="danger" plain size="mini" @click="deleteRow(row)">删除</el-button>
            </template>
            <!-- Echarts 柱形统计图插槽 -->
            <!-- <template #echarts> -->
                <!-- Echarts 柱形统计图的代码 -->
                <!-- <div id="echartsContainer" style="margin: auto; width: 500px; height: 500px;"></div> -->
            <!-- </template> -->
        </selectFromBank>
        <addItem @dataEdit="handleFormEdit" ref="addItemRef" />
    </div>
</template>

<script setup>
import { ref, reactive, computed, inject, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import addItem from './addItem.vue'
import selectFromBank from '@/components/selectFromBank.vue';
import { deleteTitleData, getTotalTitle,getTotalTitleNum } from '@/api/questionBank';
import { useRoute } from 'vue-router';
import { getIdSubject } from '@/api/subject.js'
import { getAllExamineContent } from '@/api/tag'
import * as echarts from 'echarts';

// const searchId = ref('');
// const searchSubject = ref('');
// const searchType = ref('');
// const searchContent = ref('');
// const pageSize = ref(10);
// const currentPage = ref(1);
const addItemRef = ref()
const dataArr = reactive([]);
const isRefresh =  ref()

// const totalTitleCount = reactive({
//     titalCount:0,
//     oneQuestion: 0,
//     multipleQuestion: 0,
//     trueOrFalse: 0,
//     gapFilling: 0,
//     bigTitle: 0
// })

const handleFormEdit = (arr) => {
    let index = -1;
    console.log(dataArr[0].id, 'dataaaaaaa');
    for (let i = 0; i < dataArr.length; i++) {
        if (dataArr[i].id === arr.id) {
            index = i;
            break;
        }
    }
    if (index !== -1) {
        // 假设更新整个对象，你也可以根据需要单独更新某个属性
        // Object.assign(dataArr[index], arr);是一种用于更新对象的方法。它将 arr 对象中的所有属性值分配到 dataArr[index] 对象的对应属性中。
        Object.assign(dataArr[index], arr);

    } else {
        // 如果没有找到相同 id 的元素，可能是新增的数据，可以将它添加到 dataArr 中
        dataArr.push(arr);
    }
    // 这里可以调用重新计算总题目数量的函数，确保数据的一致性
    // totalTitle();
}

// 删除操作
const deleteRow = async (row) => {
    const confirmResult = await ElMessageBox.confirm(
        '是否删除',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).catch(() => {
        ElMessage({
            type: 'info',
            message: '删除取消',
        });
    });
    if (confirmResult === "confirm") {
        // 等待用户点击确认按钮
        try {
            // 异步删除行的操作
            let index
            for (let i = 0; i <= dataArr.length; i++) {
                if (dataArr[i].id === row.id) {
                    //相等后将找到的id交给index后退出循环
                    index = dataArr[i].id
                    break
                }
            }
            //把删除的id传给后端
            const res = await deleteTitleData(index)
            console.log(res, 'resDelete');
            if(res.data.code === 403){
                ElMessage({
                type: 'error',
                message: `${res.data.msg}`,
                });
                return
            }
            // 删除成功后刷新页面
            // location.reload();
            dataArr.splice(dataArr.indexOf(row), 1);

            // getPageData()
            ElMessage({
                type: 'success',
                message: '删除成功',
            });
        } catch (error) {
            console.error(error);
        } finally {
            // resetDeleteConfirm();
        }
    }
}

const addOrEditItem = (row) => {

    addItemRef.value.open(row)
}

const route = useRoute()
//传过来的id为string，将他变为int
// let num = parseInt(route.params.subId)

//获取到科目全部题
const getTitle = async () => {
    // const res = await getSubjectTitle()
    const res = await getTotalTitle(num)
    // const res = await getTotalTitle(1)
    //获取当前页面科目
    const res1 = await getIdSubject(route.params.subId)
//   const res1 = await getIdSubject(1)
    const res1Data = res1.data.data
    const responseData = res.data.data
    responseData.forEach((response) => {
        const questionData = {
            id: response.id,
            type: response.type,
            questionContent: response.questionContent,
            answer: response.answer,
            score: response.score,
            difficulty: response.difficulty,
            createdAt: response.createdAt,
            options: response.options,
            subject: res1Data.subject
        }
        dataArr.push(questionData)
    })
}

const Refresh = (data) =>{
    isRefresh.value = data
}

//获取标签信息
const getTag = async () =>{
    const res = await getAllExamineContent(1)
}

onMounted(async () => {
    Refresh()
//获取标签信息
    getTag()
    if(isRefresh.value){
        //获取到科目全部题
        getTitle()
        isRefresh.value = false
    }

  //题目数量统计
//     let num = parseInt(route.params.subId)
//     const resNum = await getTotalTitleNum(num)
//      // 初始化 Echarts 实例
//      const myChart = echarts.init(document.getElementById('echartsContainer'));

// // 准备数据
// const data = [
//   { name: '单项选择题', value: resNum.data.单项选择题},
//   { name: '多项选择题', value: resNum.data.多项选择题 },
//   { name: '填空题', value: resNum.data.填空题 },
//   { name: '判断题', value: resNum.data.判断题 },
//   { name: '组合题', value: resNum.data.组合题 }
// ];

// // 绘制柱形统计图
// myChart.setOption({
//   title: {
//     text: '题目类型统计',
//     x:'center'
//   },
//   tooltip:{
//     trigger:"axis",//垂直线
//     axisPointer:{
//         type:'cross'//十字线
//     }

//   },
//   xAxis: {
//     type: 'category',
//     data: data.map(item => item.name),
//     axisLabel: {
//             // inside: true,
//             // color: '#fff'
//         },
//         axisTick: {
//             show: false
//         },
//         axisLine: {
//             show: false
//         },
//         z: 10
//   },
//   yAxis: {
//     type: 'value',
//     axisLine: {
//             show: false
//         },
//         axisTick: {
//             show: false
//         },
//         axisLabel: {
//             color: '#999'
//         } 
//   },
//   series: [{
//     data: data.map(item => item.value),
//     type: 'bar',
//     showBackground: true,
//     itemStyle: {
//         color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
//             { offset: 0, color: '#83bff6' },
//             { offset: 0.5, color: '#188df0' },
//             { offset: 1, color: '#188df0' }
//         ])
//     },
//     emphasis: {
//         itemStyle: {
//             color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
//                 { offset: 0, color: '#2378f7' },
//                 { offset: 0.7, color: '#2378f7' },
//                 { offset: 1, color: '#83bff6' }
//             ])
//         }
//     }, 
//   }]
// });

})
</script>


<style scoped>
  .card {
    /* width: 900px; */
    /* width: 100%; */
    margin: 0 auto;
    padding: 20px;
    background-color: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, .1);
    transition: box-shadow .3s ease;
    justify-content:center;
    display:flex;
}
.el-pagination {
    display: flex;
    margin-top: 20px;
    /* margin: 20px auto; */
    justify-content: center;
}

.el-card {
    width: 100px;
    height: 30px;
    line-height: 30px;
}

.topCard {
    display: flex;
    box-sizing: border-box;
    width: 100%;
    height: 30px;
    line-height: 30px;
    /* background-color: pink; */
    margin-bottom: 10px;
}

.topCard .cla {
    width: 160px;
    /* margin: 0 20px; */
    margin-right: 20px;
    border: 1px solid #dcdfe6;
    /* align-items: center; */
    text-align: center;
    color: #9ea0a3;
    font-size: 13px;
    border-radius: 5px;
}
</style>